<template>
  <div class="x-state-box">
    <div class="header-box">
      <div class="title"><span>{{data.title}}</span></div>
      <div class="header-msg-box">
        <div class="part">
          <i class="fa fa-thermometer-three-quarters icon"></i>
          <span>{{temperature}}℃</span>
          <div class="part-tip">
            温度：{{temperature}}℃ 
          </div>
        </div>
        <div class="part">
          <i class="fa fa-tint icon"></i>
          <span>{{humidity}}%</span>
          <div class="part-tip">
            湿度：{{humidity}}% 
          </div>
        </div>
        <div class="part" @click="alert">
          <img src="../../../../assets/images/monitor.png" alt="" class="part-img">
          <span>监控</span>
        </div>
      </div>
    </div>
    <div class="content-box row">
      <div class="content col-12" v-for="phase in phasesList">
        <div class="icon-box">
          <div class="name"><span>进线柜</span></div>
          <div class="icon" @click="onShowWorkedChart(phase.ioId, phase.ioData === 1)" :class="{'phase-state-run': phase.ioData === 1, 'phase-offline': !(phase.ioData === 1)}" ></div>
          <div class="state" :class="{'gray-color': !(phase.ioData === 1)}">
            <span v-show="phase.ioData === 1">运行</span>
            <span v-show="!(phase.ioData === 1)">离线</span>
          </div>
        </div>
        <div class="msg-box">
          <div class="part part1">
            <div class="msg">
              <span class="mr10">A:</span>
              <span>{{phase.aVoltage || '-'}}</span> <span class="unit mr20">V</span>
              <span>
                {{ phase.aElectric || '-'}}
                </span>
                <span class="unit">A</span>
            </div>
            <div class="msg">
              <span class="mr10">B:</span>
              <span>{{phase.bVoltage || '-'}}</span> <span class="unit mr20">V</span>
              <span>
                {{ phase.bElectric || '-'}}</span>
                <span class="unit">A</span>
            </div>
            <div class="msg">
              <span class="mr10">C:</span>
              <span>{{phase.cVoltage || '-'}}</span> <span class="unit mr20">V</span>
              <span>
                {{ phase.cElectric || '-'}}</span>
                <span class="unit">A</span>
            </div>
          </div>
          <div class="part part2">
            <div class="msg">
              <span class="mr10">总功率因素:</span>
              <!--<span :class="{'red-color': attrIsAlert('power', phase)}">-->
              <span>
                {{ phase.power || '-'}}
              </span>
            </div>
            <div class="msg">
              <span class="mr10">总有功率功率:</span>
              <span>
                {{ phase.psum || '-' }}
              </span>
              <span class="unit">KW</span></div>
          </div>
          <div class="part part3">
            <div class="x-chart-box" @click.stop.prevent="onShowChart(phase.id)">
              <broken-line :width="colWidth" height="60px" :series-data="chartData[phase.id]"></broken-line>
              <div class="chart-box-shelter"></div>
              <!--<div class="event-mark" @click="onShowChart(phase.id)"></div>-->
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import api from 'api'
import DEVICE_TYPES from 'config/device-types'
import PRODUCTIDS from 'config/product-ids'
// import filters from 'filters'

const DATA_ALERT = {
  temperature: {
    min: 0,
    max: 40
  },
  humidity: {
    min: -1000,
    max: 1000
  },
  aElectric: {
    min: 0,
    max: 380
  },
  bElectric: {
    min: 0,
    max: 380
  },
  cElectric: {
    min: 0,
    max: 380
  },
  // 设置为无上下限
  power: {
    min: -1000,
    max: 1000
  },
  psum: {
    min: 0,
    max: 470
  }
}

export default {
  name: 'State',

  props: {
    data: {
      default: null
    }
  },

  data () {
    return {
      colWidth: '160px',
      deviceOnLine: false,
      psumHistorys: [],
      phasesTemp: [],
      popUpShow: false
    }
  },

  computed: {
    temperature () {
      let res = _.cloneDeep(this.$store.getters.eleTempHumidity)
      let tem = '-'
      res.forEach(item => {
        this.data.devices.forEach(element => {
          if (element.id === item.id) {
            tem = item.data['13']
          }
        })
      })
      return tem
    },
    humidity () {
      let res = this.$store.getters.eleTempHumidity
      let hum = '-'
      res.forEach(item => {
        this.data.devices.forEach(element => {
          if (element.id === item.id) {
            hum = item.data['14']
          }
        })
      })
      return hum
    },
    // ioOnline () {
    //   let res = this.$store.getters.switch
    //   let io
    //   res.forEach(item => {
    //     this.data.devices.forEach(element => {
    //       if (element.id === item.id) {
    //         io = item.online
    //       }
    //     })
    //   })
    //   return io
    // },
    ioStatus () {
      // let res = this.$store.getters.switch
      // let io = []
      // res.forEach(item => {
      //   this.data.devices.forEach(element => {
      //     if (element.id === item.id) {
      //       io.push(item)
      //     }
      //   })
      // })
      // return io
    },
    phases () {
      return this.$store.getters.phase
    },
    phasesList () {
      let res = this.$store.getters.switch
      let io = []
      if (res.length !== 0) {
        res.forEach(item => {
          this.data.devices.forEach(element => {
            if (element.id === item.id) {
              io.push(item)
            }
          })
        })
      }
      let result = []
      result = _.filter(this.data.devices, (item) => {
        return item.type === DEVICE_TYPES.PHASE
      })
      // 加入io设备ID和io设备的数据
      // 根据序号来判断是否
      if (io.length !== 0) {
        result.forEach((element, i) => {
          io.forEach((item, index) => {
            if (item.serialNumber === element.serialNumber) {
              element['ioId'] = item.id
              element['ioData'] = item.data['4']
              if (this.data.title === '1栋配电房') {
                console.log(result)
              }
            }
          })
        })
      }
      // // 加入Io设备ID
      // this.data.devices.forEach(item => {
      //   result.forEach(element => {
      //     if (item.type === DEVICE_TYPES.SWITCH) {
      //       element['ioId'] = item.id
      //     }
      //   })
      // })
      if (this.phases.length !== 0) {
        result.forEach((item) => {
          let finded = _.find(this.phases, (ele) => {
            return item.id === ele.id
          })
          if (finded) {
            item.aVoltage = finded.data['aVoltage']
            item.bVoltage = finded.data['bVoltage']
            item.cVoltage = finded.data['cVoltage']
            item.bElectric = finded.data['bElectric']
            item.aElectric = finded.data['aElectric']
            item.cElectric = finded.data['cElectric']
            item.power = finded.data['power']
            item.psum = finded.data['psum']
          }
        })
      }
      return result
    },
    chartData () {
      let result = {}
      this.psumHistorys.forEach((item) => {
        let datas = []
        item.data.forEach((data) => {
          let obj = {
            value: data['108'] || 0,
            date: new Date(data.snapshot_date)
          }
          datas.push(obj)
        })
        result[item.deviceId] = datas
      })
      return result
    },

    warn () {
      let res = false
      for (let attr in DATA_ALERT) {
        if (this.phasesList.length) {
          this.phasesList.forEach((item) => {
            if (this.attrIsAlert(attr, item)) {
              res = true
            }
          })
        }
      }
      return res
    }
  },

  mounted () {
    this.requestRestfulData()
  },

  methods: {
    // 检查三相设备是否异常
    isPhaseAlert (phase) {
      let res = false
      for (let attr in DATA_ALERT) {
        if (this.attrIsAlert(attr, phase)) {
          res = true
          break
        }
      }
      return res
    },
    // 检查某个属性是否异常
    attrIsAlert (attr, phase) {
      if (phase) {
        if (!phase[attr]) {
          return false
        }
        if (phase[attr] - 0 > DATA_ALERT[attr].max || phase[attr] - 0 < DATA_ALERT[attr].min) {
          return true
        }
        return false
      }
      // 检测温度和湿度
      if (typeof this.attr !== 'number') {
        return false
      }
      if (this.attr - 0 > DATA_ALERT[attr].max || this.attr - 0 < DATA_ALERT[attr].min) {
        return true
      }
      return false
    },
    // 判断后台返回的数据是否超出最大和最小值,超出后渲染一个默认值
    stateCommit (num) {
      if (num > 10000 || num < -10000) {
        return num > 10000 ? 10000 : -10000
      }
      return num
    },
    getPsumHistorys (productId, deviceId) {
      let params = {
        'offset': 0,
        'limit': 2500,
        'date': {
          'begin': new Date() - 1 * 1000 * 60 * 60 * 24,
          'end': +new Date()
        },
        'rule_id': '58d09973c5740e446cc94699'
      }
      api.snapshot.getSnapshot(productId, deviceId, params).then((res) => {
        this.psumHistorys.push({
          deviceId: deviceId,
          data: res.data.list
        })
      }).catch((res) => {
        this.handleError(res)
      })
    },
    requestRestfulData () {
      // let switchDeviceMsg = this.getDeviceMsg(DEVICE_TYPES.SWITCH)
      let phaseDeviceMsgs = this.getDeviceMsgs(DEVICE_TYPES.PHASE)
    //   let tempHumidityDeviceMsg = this.getDeviceMsg(DEVICE_TYPES.TEMP_HUMIDITY)

    //   this.phasesTemp = []

      // // I/O开关量检测
      // api.device.getVDevice(switchDeviceMsg.productId, switchDeviceMsg.deviceId).then((res) => {
      //   let datapoints = res.data
      //   let {
      //     '4': deviceOnLine
      //   } = datapoints

      //   this.deviceOnLine = deviceOnLine && res.data.online

      //   // // 将数据添加如vuex
      //   // this.$store.dispatch('updateElectricalDeviceStatus', {
      //   //   id: switchDeviceMsg.deviceId,
      //   //   type: DEVICE_TYPES.SWITCH,
      //   //   isWarnning: this.warn, // 是否告警
      //   //   online: this.deviceOnLine,
      //   //   data: {
      //   //     '4': this.deviceOnLine
      //   //   },
      //   //   room: this.data.title // 所属位置
      //   // })
      // }).catch((res) => {
      //   this.handleError(res)
      // })

      // // 智能温湿度变送器
      // api.device.getVDevice(tempHumidityDeviceMsg.productId, tempHumidityDeviceMsg.deviceId).then((res) => {
      //   let datapoints = res.data
      //   let {
      //     '13': temperature,
      //     '14': humidity
      //   } = datapoints

      //   this.deviceDatas.temperature = filters.toFixed(this.stateCommit(temperature)) || '-'
      //   this.deviceDatas.humidity = filters.toFixed(this.stateCommit(humidity)) || '-'

      //   // // 将数据添加如vuex
      //   // this.$store.dispatch('updateElectricalDeviceStatus', {
      //   //   id: tempHumidityDeviceMsg.deviceId,
      //   //   type: DEVICE_TYPES.TEMP_HUMIDITY,
      //   //   isWarnning: this.warn, // 是否告警
      //   //   data: {
      //   //     '13': temperature,
      //   //     '14': humidity
      //   //   },
      //   //   room: this.data.title // 所属位置
      //   // })
      // }).catch((res) => {
      //   this.handleError(res)
      // })

      phaseDeviceMsgs.deviceIds.forEach((id) => {
        // 智能三相电力监控仪7天历史
        this.getPsumHistorys(phaseDeviceMsgs.productId, id)
    //     // 智能三相电力监控仪
    //     // api.device.getVDevice(phaseDeviceMsgs.productId, id).then((res) => {
    //     //   let datapoints = res.data
    //     //   let {
    //     //     '101': aVoltage,
    //     //     '102': aElectric,
    //     //     '103': bVoltage,
    //     //     '104': bElectric,
    //     //     '105': cVoltage,
    //     //     '106': cElectric,
    //     //     '107': power,
    //     //     '108': psum
    //     //   } = datapoints

    //     //   let obj = {}
    //     //   obj.id = id
    //     //   obj.aVoltage = filters.toFixed(this.stateCommit(aVoltage), 2) || '-'
    //     //   obj.bVoltage = filters.toFixed(this.stateCommit(bVoltage), 2) || '-'
    //     //   obj.cVoltage = filters.toFixed(this.stateCommit(cVoltage), 2) || '-'
    //     //   obj.bElectric = filters.toFixed(this.stateCommit(bElectric), 2) || '-'
    //     //   obj.aElectric = filters.toFixed(this.stateCommit(aElectric), 2) || '-'
    //     //   obj.cElectric = filters.toFixed(this.stateCommit(cElectric), 2) || '-'
    //     //   obj.power = filters.toFixed(this.stateCommit(power), 2) || '-'
    //     //   obj.psum = filters.toFixed(this.stateCommit(psum), 2) || '-'

    //     //   this.phasesTemp.push(obj)

    //     //   if (this.phasesTemp.length === phaseDeviceMsgs.deviceIds.length) {
    //     //     this.phases = this.phasesTemp
    //     //   }

    //     //   this.$store.dispatch('updateElectricalDeviceStatus', {
    //     //     id: id,
    //     //     type: DEVICE_TYPES.PHASE,
    //     //     online: res.data.online,
    //     //     isWarnning: this.isPhaseAlert(obj),
    //     //     data: {
    //     //       '101': aVoltage,
    //     //       '102': aElectric,
    //     //       '103': bVoltage,
    //     //       '104': bElectric,
    //     //       '105': cVoltage,
    //     //       '106': cElectric,
    //     //       '107': power,
    //     //       '108': psum
    //     //     },
    //     //     room: this.data.title // 所属位置
    //     //   })
    //     // }).catch((res) => {
    //     //   this.handleError(res)
    //     // })
      })
    },

    getDeviceMsgs (type) {
      let productId = PRODUCTIDS[type]
      let deviceIds = []
      this.data.devices.forEach((device) => {
        if (device.type === type) {
          deviceIds.push(device.id)
        }
      })
      return {productId, deviceIds}
    },

    getDeviceMsg (type) {
      let productId = PRODUCTIDS[type]
      let deviceId
      this.data.devices.forEach((device) => {
        if (device.type === type) {
          deviceId = device.id
        }
      })
      return {productId, deviceId}
    },
    onShowChart (deviceId) {
      this.$emit('showchart', {
        productId: PRODUCTIDS[DEVICE_TYPES.PHASE],
        deviceId: deviceId
      }, this.data.title)
    },
    onShowWorkedChart (deviceId, deviceStatus) {
      let stauts = deviceStatus === true ? 1 : 0
      this.$emit('showWorkedChart', {
        productId: PRODUCTIDS[DEVICE_TYPES.SWITCH],
        ioProductId: PRODUCTIDS[DEVICE_TYPES.SWITCH],
        chartDeviceMsg: stauts,
        deviceId: deviceId
      }, this.data.title)
    },
    alert () {
      window.alert('请在内网查看')
    }
  }
}
</script>

<style lang="stylus" scoped>

  .x-state-box
    width: 100%;
    height: 100%;
    background: #1e1e1e;
    border: 1px solid #1e1e1e;
    padding 10px
    box-sizing border-box

    .header-box
      color: #ccc;
      height: 80px;
      line-height: 30px;
      font-size: 13px;
      border-bottom 1px solid #444
      box-sizing border-box

      .title
        font-size 14px

      .part
        display inline-block
        position relative
        cursor pointer
        margin-left 10px
        margin-right 20px
        height 50px
        line-height 50px
        font-size 16px
        color #999
        .part-img
          vertical-align: middle;
          margin-bottom: 8px;
          width: 23px;
        .icon
          margin-right 5px
          font-size 18px
        .part-tip
          font-size 12px
          position absolute
          top 36px
          left 0px
          width 85px
          padding-left 10px
          height 32px
          line-height 32px
          background #2B2B2B
          border-radius 5px
          color #ccc
          display none
      .part-pop-up
        font-size: 17px;
        position: absolute;
        top: 93px;
        left: 197px;
        width: 190px;
        padding-left: 21px;
        height: 62px;
        z-index: 100;
        line-height: 65px;
        background: #2b2b2b;
        border-radius: 5px;
        color: #ccc;
        display: inline-block;
        .part-pop-up-close
          border: 1px solid #fff;
          pointer-events: auto;
          cursor: pointer;
          z-index: 200;
          padding: 0 7px;
          margin-left: 23px;
          font-size: 12px;
          border-radius: 5px;
          height: 26px;
          line-height: 26px;
          z-index: 999;
        &:hover .part-tip{
          display block
        }


    .content-box
      position relative
      display: flex
      justify-content: space-around
      width 100%
      .content
        position relative
        box-sizing border-box
        height 210px
        width 300px
        justify-content: center
        display: flex


      .icon-box
        left 0
        height 100%
        width 120px
        padding-left 0px
        padding-top 20px
        padding-right 20px
        box-sizing border-box

        .name
          text-align left
          font-size 14px
          padding-left 10px
          box-sizing border-box

        .icon
          width 100%
          height 110px
          background no-repeat right top / 110% auto
          cursor pointer

        .state
          text-align center
          font-size 14px
          font-weight 100
      .msg-box
        height 100%
        padding-top 10px
        box-sizing border-box
        .part
          padding-top 10px
          .msg
            line-height 22px
        .part3
          .x-chart-box
            position relative
            cursor pointer
            .chart-box-shelter
              position absolute
              cursor pointer
              font-size 0
              bottom 5px
              height 50px
              width 155px
        .unit
          color #999

  .phase-state-run
    background-image url('../../../../assets/images/u59.png') !important
  .phase-state-warn
    background-image url('../../../../assets/images/u237.png') !important
  .phase-offline
    background-image url('../../../../assets/images/u392.png') !important
  .phase-offline
  .gray-color
    color #999
</style>
